package com.lmf.cloud.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * @Description TODO
 * <p>
 * Copyright @2022 Shanghai Mise Co. Ltd.
 * All right reserved.
 * <p>
 * @Author LiuMingFu
 * @Date 2024/7/18 15:37
 */
@Slf4j
@Tag(name = "测试服务", description = "测试接口crud")
@RequestMapping("/loadBalancer")
@RestController
public class MyDataController {

    @Value("${server.port}")
    private int port;

    @Resource
    private RestTemplate restTemplate;
    //loadBalancer客户端
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/discovery")
    public String discovery() {
        //获取所有注册的服务列表
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        //获取指定服务名称的实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-provider-payment8001");
        for (ServiceInstance element : instances) {
            //打印服务具体的ip、端口、url
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t" + element.getUri());
        }

        return instances.get(0).getServiceId() + ":" + instances.get(0).getPort();
    }


    @RequestMapping("/getData")
    public String getData(@RequestParam(required = false) String name) {
        log.info("cloud-nacos-loadBalancer-consumer-9002：name={}", name);
        //会自动将微服务的名称转换为对应的ip地址，如果是集群服务，自动处理负载均衡
        String result = restTemplate.postForObject("http://cloud-provider-payment8001/getData2?name=" + name, null, String.class);
        log.info("result={}", result);
        return "cloud-nacos-loadBalancer-consumer-9002：当前使用的服务端口=" + port + "，提供者服务调用结果：" + result;
    }


    @Operation(summary = "获取数据", description = "获取数据")
    @RequestMapping("/hello")
    public String getData2(@RequestParam(required = false) String name) {
        System.out.println(name);
//        int i = 1 / 0; 
        return "当前使用的服务端口=" + port;
    }
}
